import Util from '../../utils/util.js';
// import { login } from '../../api/user.js';
let app = getApp();

Component({
  properties: {

    iShidden: {
      type: Boolean,
      value: true,
    },
    //是否自动登录
    isAuto: {
      type: Boolean,
      value: true,
    },
    isGoIndex: {
      type: Boolean,
      value: true,
    },
  },
  data: {
    cloneIner: null,
    loading: false,
    errorSum: 0,
    errorNum: 3
  },
  attached() {
    if (this.data.isAuto) {
      this.setAuthStatus();
    }
  },
  methods: {
    close() {
      let pages = getCurrentPages();
      let currPage = pages[pages.length - 1];
      if (this.data.isGoIndex) {
        wx.switchTab({url: '/pages/index/index'});
      } else {
        this.setData({
          iShidden: true
        });
        if (currPage && currPage.data.iShidden != undefined) {
          currPage.setData({iShidden: true});
        }
      }
    },

    //检测登录状态并执行自动登录
    setAuthStatus() {
      var that = this;

      Util.chekWxLogin().then((res) => {

        // console.log("auth login : " + JSON.stringify(res))
        let pages = getCurrentPages();
        let currPage = pages[pages.length - 1];

        if (currPage && currPage.data.iShidden != undefined) {
          currPage.setData({iShidden: true});
        }

        if (res.isLogin) {
          if (!Util.checkLogin())
            return Promise.reject({authSetting: true, msg: '用户token失效', userInfo: res.userInfo});
          that.triggerEvent('onLoadFun', app.globalData.userInfo);

          that.setData({iShidden: true});
        } else {
          // wx.showLoading({ title: '正在登录中' });
          that.setData({iShidden: false});
        }
      }).catch(res => {
        //自动弹出授权
        that.setData({iShidden: false});
      })

    },

    //授权
    setUserInfo(userInfo) {
      let that = this;
      wx.showLoading({title: '正在注册'});

      Util.userRegister(userInfo).then(res => {
        wx.hideLoading()
        that.setData({iShidden: true});
        that.triggerEvent('onLoadFun', app.globalData.userInfo)
      }).catch(errmsg => {
        wx.hideLoading();
        that.data.errorSum++;
        that.setData({errorSum: that.data.errorSum});

        that.setData({iShidden: true});
        if (that.data.errorSum >= that.data.errorNum) {
          app.Tips({title: errmsg});
        } else {
          that.setUserInfo(userInfo);
        }
      })

    },

    getWxUserInfo: function (e) {
      let that = this;
      Util.wxgetUserInfo().then(res => {
        that.setUserInfo(res)
      }).catch(errmsg => {
        app.Tips({title: errmsg})
      })
    }

  },
})